package com.wsf.demo.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{pageCode}")
@Component
public class WebSocketController {

    // 获取类名称
    private static final String loggerName = WebSocketController.class.getName();

    private static Map<String, List<Session>> electricSocketmap = new ConcurrentHashMap<String, List<Session>>();

    @OnOpen
    public void onOpen(@PathParam("pageCode") String pageCode, Session session) {
        List<Session> sessions = electricSocketmap.get(pageCode);
        if (null == sessions) {
            List<Session> sessionList = new ArrayList<>();
            sessionList.add(session);
            electricSocketmap.put(pageCode, sessionList);
        } else {
            sessions.add(session);
        }
    }

    // 收到调用的信息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {

        System.out.println("接收到信息" + message);
        session.getBasicRemote().sendText("我推送的信息是" + message);

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生了错误");
    }

    @OnClose
    public void onClose(@PathParam("pageCode") String pageCode, Session session) {
        if (electricSocketmap.containsKey(pageCode)) {
            System.out.println("aaaaaaaaaaa");
            electricSocketmap.get(pageCode).remove(session);
        }
        System.out.println("bbbbbbbbbbb");
    }

}
